/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.myself;

import android.app.ActivityGroup;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.delivery.InvoiceMainActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.global.DanluApplication;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.RegisterEditText;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.dhc.danlu.widget.holder.NoramlInvoiceHolder;
import cn.com.dhc.danlu.widget.holder.VatInvoiceHolder;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.request.mydl.invoice.AddInvoiceRequest;
import cn.com.hd.mall.web.webservices.entity.request.mydl.invoice.AddInvoiceRequest.AddInvoiceModel;
import cn.com.hd.mall.web.webservices.entity.request.mydl.invoice.DelInvoiceRequest;
import cn.com.hd.mall.web.webservices.entity.request.mydl.invoice.ModifyInvoiceRequest;
import cn.com.hd.mall.web.webservices.entity.request.mydl.invoice.ModifyInvoiceRequest.ModifyInvoiceModel;
import cn.com.hd.mall.web.webservices.entity.request.mydl.invoice.SetDefaultInvoiceRequest;
import cn.com.hd.mall.web.webservices.entity.response.mydl.invoice.AddModifyInvoiceResponse;
import cn.com.hd.mall.web.webservices.entity.response.mydl.invoice.InvoiceListResponse;
import cn.com.hd.mall.web.webservices.entity.response.mydl.invoice.InvoiceListResponse.InvoiceListModel;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

import static cn.com.dhc.danlu.R.id.InvoiceAddtxt;
import static cn.com.dhc.danlu.R.string.invoice_dell_fail;
import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-01-16 14:32<br/>
 *
 * <p>
 * 我发票的页面
 * </p>
 */
//public class MyInvoiceActivity extends AsyncTaskActivityGroup {
public class MyInvoiceActivity extends ActivityGroup {
    /**
     * 普通发票类型
     */
    public static final String NORMAL_INVOICE_TYPE = "N011";
    /**
     * 增值税发票类型
     */
    public static final String VAT_INVOICE_TYPE = "N012";
    /**
     * 返回按钮
     */
    protected LinearLayout llytBack;

    /**
     * 添加普通发票
     */
    private TextView tvInvoiceAddtxt;
    /**
     * 下拉刷新容器
     */
    private PtrClassicFrameLayout ptrdd;
    /**
     * Activity容器
     */
    private LinearLayout invoiceContainer;
    /**
     * 没有数据
     */
    private LinearLayout llytNoData;
    /**
     * 有数据
     */
    private LinearLayout llytHasData;
    /**
     * 没有数据 title1
     */
    private TextView tvNoDataTitle1;
    /**
     * 没有数据 title2
     */
    private TextView tvNoDataTitle2;
    /**
     * 普通发票tab
     */
    private LinearLayout llytNormalInvoice;
    /**
     * 增值税发票tab
     */
    private LinearLayout llytVatInvoice;
    /**
     * 普通发票址UI元素List
     */
    private List<NoramlInvoiceHolder> noramlInvoiceHolders;
    /**
     * LayoutInflater
     */
    private LayoutInflater layoutInflater;
    /**
     * 保存按钮
     */
    private Button saveVatInvoice;
    /**
     * 发票模型
     */
    private InvoiceListModel vatUserInvoice;
    /**
     * 增值发票Holder
     */
    private VatInvoiceHolder vatInvoiceHolder;
    /**
     * 发票模型List
     */
    private List<InvoiceListModel> norUserInvoices;
    /**
     * 发票ID
     */
    private int selectViewId;
    private boolean saveNoramlFlag = false;
    private boolean saveVatFlag = false;
    private int invoiceType;
    private int intentInvoiceType;
    private String intentNoramalId;
    /**
     * 设置监听
     */
    private View.OnClickListener onClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int index;
            switch (v.getId()) {
                // 返回
                case R.id.llytBack:
                    Intent intent = new Intent(MyInvoiceActivity.this, InvoiceMainActivity.class);
                    intent.putExtra(CommonConst.IntentKey.INVOICE_ID, intentInvoiceType);
                    intent.putExtra("InvoiceId", intentNoramalId);
                    setResult(RESULT_OK, intent);
                    finish();
                    break;

                case R.id.llytNormalInvoice:  // 普通发票Tab
                    intentInvoiceType = CommonConst.InvoiceConst.ID_NORMAL_INVOICE;
                    // 普通发票Tab
                    selectTabLayout(R.id.llytNormalInvoice);
                    tvInvoiceAddtxt.setVisibility(View.VISIBLE);
                    saveVatInvoice.setVisibility(View.GONE);
                    if (norUserInvoices != null && norUserInvoices.size() > 0) {
                        buildNorInvoiceList(norUserInvoices);
                        llytNoData.setVisibility(View.GONE);
                        llytHasData.setVisibility(View.VISIBLE);
                    } else {
                        llytHasData.setVisibility(View.GONE);
                        llytNoData.setVisibility(View.VISIBLE);
                    }
                    break;

                case R.id.llytVatInvoice: // 增值税发票Tab
                    intentInvoiceType = CommonConst.InvoiceConst.ID_ADD_INVOICE;
                    // 增值税发票Tab
                    selectTabLayout(R.id.llytVatInvoice);
                    tvInvoiceAddtxt.setVisibility(View.GONE);
                    saveVatInvoice.setVisibility(View.VISIBLE);
                    if (saveVatFlag) {
                        getInvoiceList();
                        saveVatFlag = false;

                    } else {
                        buildVatInvoiceList(vatUserInvoice);
                    }
                    llytHasData.setVisibility(View.VISIBLE);
                    llytNoData.setVisibility(View.GONE);
                    break;

                case InvoiceAddtxt:
                    // 添加普通发票
                    noramlInvoiceAddDialog(InvoiceAddtxt, null);
                    break;

                case R.id.setNoramlInvoice:
                    // 设为默认
                    index = (Integer) v.getTag();
                    if (norUserInvoices.get(index).getIsDefault().equals(CommonConst.InvoiceConst.INVOICE_NO_DEFAU)) {
                        SetDefaultInvoiceRequest setDefaultInvoiceRequest = new SetDefaultInvoiceRequest();
                        setDefaultInvoiceRequest.setToken(agent.getToken());
                        setDefaultInvoiceRequest.setInvoiceId(norUserInvoices.get(index).getInvoiceId());
                        setDefauInvoice(setDefaultInvoiceRequest);
                    }
                    break;

                // 编辑普通发票
                case R.id.editInvoice:
                    index = (Integer) v.getTag();
                    InvoiceListModel userInvoices = norUserInvoices.get(index);
                    noramlInvoiceAddDialog(R.id.editInvoice, userInvoices);
                    break;

                // 删除普通发票
                case R.id.deleteInvoice:
                    index = (Integer) v.getTag();
                    InvoiceListModel userInvoice = norUserInvoices.get(index);
                    noramlInvoiceAddDialog(R.id.deleteInvoice, userInvoice);
                    break;

                case R.id.saveVatInvoice:
                    // 保存增值税发票
                    saveVatInvoice();
                    break;

                default:
                    break;
            }
        }
    };

    /**
     * 设置默认发票
     */
    private void setDefauInvoice(SetDefaultInvoiceRequest setDefaultInvoiceRequest) {
        agent.getApi().setDefauInvoice(setDefaultInvoiceRequest).compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>() {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        ToastUtil.getInstance().show(R.string.set_sucess);
                        getInvoiceList();
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        String displayMsg = "";
                        switch (code) {
                            case "1":
                                displayMsg = DanluApplication.get().getString(R.string.add_shopping_cart_error_1);
                                getInvoiceList();
                                break;
                            case "2":
                                displayMsg = DanluApplication.get().getString(R.string.tips_not_allowed_modify);
                                break;
                            case "3":
                                displayMsg = DanluApplication.get().getString(invoice_dell_fail);
                                getInvoiceList();
                                break;
                            default:
                                break;
                        }
                        return displayMsg;
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(DanluApplication.get().getString(R.string.set_fail) + ":" + displayMessage);
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 实例化画面控件
        //        getDelegate ().setContentView (R.layout.layout_my_invoice, R.layout_my_invoice.class);
        setContentView(R.layout.activity_my_invoice);

        initView();
        setViews();
    }

    /**
     * 页面初始化
     */
    private void setViews() {
        Intent intent = getIntent();
        intentInvoiceType = CommonConst.InvoiceConst.ID_NORMAL_INVOICE;
        if (intent != null) {
            invoiceType = intent.getIntExtra(
                    CommonConst.IntentKey.INVOICE_ID, 2);
            if (invoiceType == CommonConst.InvoiceConst.ID_ADD_INVOICE) {
                intentInvoiceType = CommonConst.InvoiceConst.ID_ADD_INVOICE;
                selectTabLayout(R.id.llytVatInvoice);
                saveVatInvoice.setVisibility(View.VISIBLE);
            } else if (invoiceType == CommonConst.InvoiceConst.ID_NORMAL_INVOICE) {
                selectTabLayout(R.id.llytNormalInvoice);
                intentInvoiceType = CommonConst.InvoiceConst.ID_NORMAL_INVOICE;
            }
        } else {
            // 显示首页Tab
            selectTabLayout(R.id.llytNormalInvoice);
        }
        layoutInflater = LayoutInflater.from(this);
        // 获取发票列表
        getInvoiceList();
        // 设置监听
        setListener();

    }

    /**
     * Tab选中效果
     *
     * @param viewId
     *         选中Tab的Id
     */
    private void selectTabLayout(int viewId) {
        // 普通发票Tab
        if (R.id.llytNormalInvoice == viewId) {
            llytNormalInvoice.setBackgroundColor(getResources().getColor(R.color.invoice_checked));
            tvInvoiceAddtxt.setVisibility(View.VISIBLE);
        } else {
            llytNormalInvoice.setBackgroundColor(getResources().getColor(R.color.invoice_not_checked));
            tvInvoiceAddtxt.setVisibility(View.GONE);
        }

        // 增值税发票Tab
        if (R.id.llytVatInvoice == viewId) {
            llytVatInvoice.setBackgroundColor(getResources().getColor(R.color.invoice_checked));
            tvInvoiceAddtxt.setVisibility(View.GONE);
        } else {
            llytVatInvoice.setBackgroundColor(getResources().getColor(R.color.invoice_not_checked));
        }
        selectViewId = viewId;
    }

    /**
     * 获取发票信息
     */
    private void getInvoiceList() {
        // 设置参数：会话验证标识
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.setToken(agent.getToken());
        // 获取发票信息
        agent.getApi().getInvoiceList(baseRequest).compose(OperatorUtils.<InvoiceListResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<InvoiceListResponse>(MyInvoiceActivity.this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(InvoiceListResponse invoiceListResponse) {
                        refreshUI(invoiceListResponse);
                    }
                });
    }

    /**
     * 设置监听
     */
    private void setListener() {
        // 普通发票监听
        llytNormalInvoice.setOnClickListener(onClickListener);
        // 增值税发票监听
        llytVatInvoice.setOnClickListener(onClickListener);
        // 增加普通发票监听
        tvInvoiceAddtxt.setOnClickListener(onClickListener);
        // 增值税发票保存监听
        saveVatInvoice.setOnClickListener(onClickListener);
        // 返回键监听
        llytBack.setOnClickListener(onClickListener);
        ptrdd.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return false;
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                frame.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        frame.refreshComplete();
                    }
                }, 2000);
            }
        });
    }

    /**
     * 更新UI显示
     */
    private void refreshUI(InvoiceListResponse invoiceListResponse) {
        if (invoiceListResponse != null) {
            if (invoiceListResponse.getSuccess().equals(CommonConst.InvoiceConst.INVOICE_RESPONSE_SUCCESS_0)) {
                norUserInvoices = new ArrayList<>();
                // 获取增值税发票数据
                vatUserInvoice = invoiceListResponse.getVatInvoice();
                buildVatInvoiceList(vatUserInvoice);
                if (invoiceListResponse.getNormalInvoiceList() != null && invoiceListResponse.getNormalInvoiceList().size() > 0) {
                    // 获取普通发票数据
                    norUserInvoices = invoiceListResponse.getNormalInvoiceList();

                    if (selectViewId == R.id.llytNormalInvoice) {
                        if (norUserInvoices != null && norUserInvoices.size() > 0) {
                            buildNorInvoiceList(norUserInvoices);
                            llytNoData.setVisibility(View.GONE);
                            llytHasData.setVisibility(View.VISIBLE);
                        } else {
                            llytHasData.setVisibility(View.GONE);
                            tvNoDataTitle1.setText(getResources().getString(R.string.no_invoice_msg1));
                            tvNoDataTitle2.setText(getResources().getString(R.string.no_invoice_msg2));
                            llytNoData.setVisibility(View.VISIBLE);
                        }
                    }
                } else {
                    if (selectViewId == R.id.llytNormalInvoice) {
                        llytHasData.setVisibility(View.GONE);
                        tvNoDataTitle1.setText(getResources().getString(R.string.no_invoice_msg1));
                        tvNoDataTitle2.setText(getResources().getString(R.string.no_invoice_msg2));
                        llytNoData.setVisibility(View.VISIBLE);
                    } else if (selectViewId == R.id.llytVatInvoice) {

                        buildVatInvoiceList(vatUserInvoice);
                        llytHasData.setVisibility(View.VISIBLE);
                        llytNoData.setVisibility(View.GONE);
                    }
                }
            }
        }
    }

    /**
     * 构建增值税发票列表
     */
    private void buildVatInvoiceList(InvoiceListModel vatUserInvoice) {
        invoiceContainer.removeAllViews();
        invoiceContainer.removeAllViewsInLayout();
        // 实例化收货地址列表item视图
        final View convertStoreView = LayoutInflater.from(this).inflate(
                R.layout.view_vat_invoice_item, invoiceContainer, false);
        vatInvoiceHolder = findStoreItemView(convertStoreView);
        if (vatUserInvoice != null) {
            if (vatUserInvoice.getCompanyName() != null) {
                vatInvoiceHolder.vatCompanyName.setText(vatUserInvoice.getCompanyName());
            }
            if (vatUserInvoice.getTaxpayerRegistrationNumber() != null) {
                vatInvoiceHolder.vatTaxpayerID.setText(vatUserInvoice.getTaxpayerRegistrationNumber());
            }
            if (vatUserInvoice.getRegisterAddress() != null) {
                vatInvoiceHolder.vatRegisterAddress.setText(vatUserInvoice.getRegisterAddress());
            }
            if (vatUserInvoice.getRegisterTel() != null) {
                vatInvoiceHolder.vatRegisterTel.setText(vatUserInvoice.getRegisterTel());
            }
            if (vatUserInvoice.getDepositBank() != null) {
                vatInvoiceHolder.vatOpenBank.setText(vatUserInvoice.getDepositBank());
            }
            if (vatUserInvoice.getAccountBank() != null) {
                vatInvoiceHolder.vatBankAcount.setText(vatUserInvoice.getAccountBank());
            }
            if (vatUserInvoice.getReceiveManName() != null) {
                vatInvoiceHolder.vatTakerName.setText(vatUserInvoice.getReceiveManName());
            }
            if (vatUserInvoice.getReceiveManTel() != null) {
                vatInvoiceHolder.vatTakerTel.setText(vatUserInvoice.getReceiveManTel());
            }
            if (vatUserInvoice.getReceiveManProvince() != null) {
                vatInvoiceHolder.vatTakerProvince.setText(vatUserInvoice.getReceiveManProvince());
            }
            if (vatUserInvoice.getReceiveManAddress() != null) {
                vatInvoiceHolder.vatDetailAddress.setText(vatUserInvoice.getReceiveManAddress());
            }
        }
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, 0, 0, 10);
        invoiceContainer.addView(convertStoreView, lp);
    }

    /**
     * 构建普通发票列表
     */
    private void buildNorInvoiceList(List<InvoiceListModel> norUserInvoices) {
        invoiceContainer.removeAllViews();
        invoiceContainer.removeAllViewsInLayout();
        if (noramlInvoiceHolders == null) {
            noramlInvoiceHolders = new ArrayList<>();
        } else {
            noramlInvoiceHolders.clear();
        }
        final int modeSize = norUserInvoices.size();
        for (int i = 0; i < modeSize; i++) {
            final View convertStoreView = layoutInflater.inflate(R.layout.view_noraml_invoice_item, null);
            final NoramlInvoiceHolder itemHolder = findNoramlStoreItemView(convertStoreView);
            String defauValue = norUserInvoices.get(i).getIsDefault();
            if (defauValue.equals(CommonConst.InvoiceConst.INVOICE_IS_DEFAU)) {
                itemHolder.noramlInvoiceName.getPaint().setFakeBoldText(true);// 加粗
                itemHolder.setDefauNoramlInvoice.setText(R.string.default_invoice);
                itemHolder.setDefauNoramlInvoice.setTextColor(getResources().getColor(R.color.order_coupon_txt_cg));
            } else {
                itemHolder.setDefauNoramlInvoice.setText(getResources().getString(R.string.set_default_invoice));
                itemHolder.setDefauNoramlInvoice.setTextColor(getResources().getColor(R.color.black));
            }
            itemHolder.noramlInvoiceName.setText(norUserInvoices.get(i).getInvoiceHeader());

            itemHolder.editInvoice.setOnClickListener(onClickListener);
            itemHolder.editInvoice.setTag(i);
            itemHolder.deleteInvoice.setOnClickListener(onClickListener);
            itemHolder.deleteInvoice.setTag(i);
            itemHolder.setDefauNoramlInvoice.setOnClickListener(onClickListener);
            itemHolder.setDefauNoramlInvoice.setTag(i);
            convertStoreView.setTag(i);

            noramlInvoiceHolders.add(itemHolder);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, 0, 0, 15);
            invoiceContainer.addView(convertStoreView, lp);
        }
    }

    /**
     * get VatInvoiceHolder by spec view container
     */
    private VatInvoiceHolder findStoreItemView(View convertView) {
        VatInvoiceHolder holder = new VatInvoiceHolder();
        holder.vatCompanyName = (RegisterEditText) convertView.findViewById(R.id.vatCompanyName);
        holder.vatTaxpayerID = (RegisterEditText) convertView.findViewById(R.id.vatTaxpayerID);
        holder.vatRegisterAddress = (RegisterEditText) convertView.findViewById(R.id.vatRegisterAddress);
        holder.vatRegisterTel = (RegisterEditText) convertView.findViewById(R.id.vatRegisterTel);
        holder.vatOpenBank = (RegisterEditText) convertView.findViewById(R.id.vatOpenBank);
        holder.vatBankAcount = (RegisterEditText) convertView.findViewById(R.id.vatBankAcount);
        holder.vatTakerName = (RegisterEditText) convertView.findViewById(R.id.vatTakerName);
        holder.vatTakerTel = (RegisterEditText) convertView.findViewById(R.id.vatTakerTel);
        holder.vatTakerProvince = (RegisterEditText) convertView.findViewById(R.id.vatTakerProvince);
        holder.vatDetailAddress = (RegisterEditText) convertView.findViewById(R.id.vatDetailAddress);
        return holder;
    }

    /**
     * get NoramlInvoiceHolder by spec view container
     */
    private NoramlInvoiceHolder findNoramlStoreItemView(View convertView) {
        NoramlInvoiceHolder holder = new NoramlInvoiceHolder();

        holder.noramlInvoiceName = (TextView) convertView.findViewById(R.id.noramlInvoiceName);
        holder.setDefauNoramlInvoice = (TextView) convertView.findViewById(R.id.setNoramlInvoice);
        holder.editInvoice = (TextView) convertView.findViewById(R.id.editInvoice);
        holder.deleteInvoice = (TextView) convertView.findViewById(R.id.deleteInvoice);

        return holder;
    }

    /**
     * 保存增值税发票
     */
    private void saveVatInvoice() {
        saveVatFlag = true;
        ModifyInvoiceRequest modifyInvoiceRequest = new ModifyInvoiceRequest();
        final ModifyInvoiceModel modifyInvoiceModel = new ModifyInvoiceModel();
        modifyInvoiceRequest.setToken(agent.getToken());
        AddInvoiceRequest request = new AddInvoiceRequest();
        AddInvoiceModel addInvoiceModel = new AddInvoiceModel();
        addInvoiceModel.setInvoiceType(VAT_INVOICE_TYPE);
        request.setToken(agent.getToken());
        if (CommonUtils.isStringBlank(vatInvoiceHolder.vatCompanyName.getText().toString())) {
            ToastUtil.getInstance().show(R.string.vat_company_name_not_null);
            return;
        }
        modifyInvoiceModel.setCompanyName(vatInvoiceHolder.vatCompanyName.getText().toString());
        addInvoiceModel.setCompanyName(vatInvoiceHolder.vatCompanyName.getText().toString());
        if (CommonUtils.isStringBlank(vatInvoiceHolder.vatTaxpayerID.getText().toString())) {
            ToastUtil.getInstance().show(R.string.vat_axpayer_id_not_null);
            return;
        }
        modifyInvoiceModel.setTaxpayerRegistrationNumber(vatInvoiceHolder.vatTaxpayerID.getText().toString());
        addInvoiceModel.setTaxpayerRegistrationNumber(vatInvoiceHolder.vatTaxpayerID.getText().toString());
        if (CommonUtils.isStringBlank(vatInvoiceHolder.vatRegisterAddress.getText().toString())) {
            ToastUtil.getInstance().show(R.string.vat_register_add_not_null);
            return;
        }
        modifyInvoiceModel.setRegisterAddress(vatInvoiceHolder.vatRegisterAddress.getText().toString());
        addInvoiceModel.setRegisterAddress(vatInvoiceHolder.vatRegisterAddress.getText().toString());
        if (!CommonUtils.isTelNumber(vatInvoiceHolder.vatRegisterTel.getText().toString())) {
            ToastUtil.getInstance().show(R.string.vat_register_tel_not_null);
            return;
        }
        modifyInvoiceModel.setRegisterTel(vatInvoiceHolder.vatRegisterTel.getText().toString());
        addInvoiceModel.setRegisterTel(vatInvoiceHolder.vatRegisterTel.getText().toString());
        if (CommonUtils.isStringBlank(vatInvoiceHolder.vatOpenBank.getText().toString())) {
            ToastUtil.getInstance().show(R.string.vat_open_bank_not_null);
            return;
        }
        modifyInvoiceModel.setDepositBank(vatInvoiceHolder.vatOpenBank.getText().toString());
        addInvoiceModel.setDepositBank(vatInvoiceHolder.vatOpenBank.getText().toString());
        if (!CommonUtils.isNumber(vatInvoiceHolder.vatBankAcount.getText().toString())) {
            ToastUtil.getInstance().show(R.string.vat_account_bank_not_null);
            return;
        }
        modifyInvoiceModel.setAccountBank(vatInvoiceHolder.vatBankAcount.getText().toString());
        addInvoiceModel.setAccountBank(vatInvoiceHolder.vatBankAcount.getText().toString());
        if (CommonUtils.isStringBlank(vatInvoiceHolder.vatTakerName.getText().toString())) {
            ToastUtil.getInstance().show(R.string.vat_taker_name_not_null);
            return;
        }
        modifyInvoiceModel.setReceiveManName(vatInvoiceHolder.vatTakerName.getText().toString());
        addInvoiceModel.setReceiveManName(vatInvoiceHolder.vatTakerName.getText().toString());
        if (CommonUtils.isStringBlank(vatInvoiceHolder.vatTakerTel.getText().toString())
                || !CommonUtils.isMobileNumber(vatInvoiceHolder.vatTakerTel.getText().toString())) {
            ToastUtil.getInstance().show(R.string.vat_taker_tel_not_null);
            return;
        }
        modifyInvoiceModel.setReceiveManTel(vatInvoiceHolder.vatTakerTel.getText().toString());
        addInvoiceModel.setReceiveManTel(vatInvoiceHolder.vatTakerTel.getText().toString());
        if (CommonUtils.isStringBlank(vatInvoiceHolder.vatTakerProvince.getText().toString())) {
            ToastUtil.getInstance().show(R.string.vat_taker_pro_not_null);
            return;
        }
        modifyInvoiceModel.setReceiveManProvince(vatInvoiceHolder.vatTakerProvince.getText().toString());
        addInvoiceModel.setReceiveManProvince(vatInvoiceHolder.vatTakerProvince.getText().toString());
        if (CommonUtils.isStringBlank(vatInvoiceHolder.vatDetailAddress.getText().toString())) {
            ToastUtil.getInstance().show(R.string.vat_taker_dati_not_null);
            return;
        }
        modifyInvoiceModel.setReceiveManAddress(vatInvoiceHolder.vatDetailAddress.getText().toString());
        addInvoiceModel.setReceiveManAddress(vatInvoiceHolder.vatDetailAddress.getText().toString());
        if (vatUserInvoice != null && vatUserInvoice.getInvoiceId() != null) {
            modifyInvoiceModel.setInvoiceId(vatUserInvoice.getInvoiceId());
            modifyInvoiceModel.setInvoiceType(vatUserInvoice.getInvoiceType());
            modifyInvoiceRequest.setInvoice(modifyInvoiceModel);
            modifyInvoice(modifyInvoiceRequest);

        } else {
            request.setInvoice(addInvoiceModel);
            addInvoice(request);
        }
    }

    /**
     * 修改发票
     *
     * @param modifyInvoiceRequest
     *         修改发票的请求体
     */
    private void modifyInvoice(ModifyInvoiceRequest modifyInvoiceRequest) {
        agent.getApi().modifyInvoice(modifyInvoiceRequest).compose(OperatorUtils.<AddModifyInvoiceResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<AddModifyInvoiceResponse>() {
                    @Override
                    public void onNext(AddModifyInvoiceResponse addModifyInvoiceResponse) {
                        switch (addModifyInvoiceResponse.getSuccess()) {
                            case "0":
                                onSuccess(addModifyInvoiceResponse);
                                break;

                            case "1": // 失败
                                ToastUtil.getInstance().show(R.string.add_shopping_cart_error_1);
                                break;

                            case "2": // 字段校验不过
                                if (addModifyInvoiceResponse.getCheckResult() != null && addModifyInvoiceResponse.getCheckResult().getFirstValue() != null) {
                                    ToastUtil.getInstance().show(addModifyInvoiceResponse.getCheckResult().getSecondValue());
                                }
                                break;

                            case "3": // -普通发票不存在
                                ToastUtil.getInstance().show(R.string.invoice_dell_fail);
                                getInvoiceList();
                                break;

                            case "4": // 普通发票抬头字数超过50
                                ToastUtil.getInstance().show(R.string.invoice_name_too_long);
                                break;

                            case "5": // 普通发票重名
                                ToastUtil.getInstance().show(R.string.invoice_add_fail);
                                break;

                            default:
                                break;
                        }
                    }
                    @Override
                    protected void onSuccess(AddModifyInvoiceResponse addModifyInvoiceResponse) {
                        // 刷新普通发票
                        if (saveNoramlFlag) {
                            getInvoiceList();
                            saveNoramlFlag = false;
                        }
                        ToastUtil.getInstance().show(R.string.edit_sucess);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "修改发票失败": displayMessage);
                    }
                });
    }

    /**
     * 添加发票
     */
    private void addInvoice(AddInvoiceRequest request) {
        //        danluTaskProxy.addInvoice(request, onAddInvoicesListener);

        agent.getApi().addInvoice(request).compose(OperatorUtils.<AddModifyInvoiceResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<AddModifyInvoiceResponse>() {
                    @Override
                    public void onNext(AddModifyInvoiceResponse addModifyInvoiceResponse) {
                        String success = addModifyInvoiceResponse.getSuccess();
                        switch (success) {
                            case "0":
                                onSuccess(addModifyInvoiceResponse);
                                break;
                            case "1":
                                ToastUtil.getInstance().show(R.string.add_shopping_cart_error_1);
                                break;
                            case "2":
                                if (addModifyInvoiceResponse.getCheckResult() != null && addModifyInvoiceResponse.getCheckResult().getFirstValue() != null) {
                                    ToastUtil.getInstance().show(addModifyInvoiceResponse.getCheckResult().getSecondValue());
                                }
                                break;
                            case "4":
                                ToastUtil.getInstance().show(R.string.invoice_add_fail);
                                break;
                            default:
                                ToastUtil.getInstance().show(R.string.add_fail);
                                break;
                        }
                    }

                    @Override
                    protected void onSuccess(AddModifyInvoiceResponse addModifyInvoiceResponse) {
                        getInvoiceList();
                        ToastUtil.getInstance().show(R.string.add_sucess);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    /**
     * 添加/编辑/删除普通发票对话框
     */
    private void noramlInvoiceAddDialog(final int viewId, final InvoiceListModel userInvoices) {
        // 创建Builder
        ViewDialog.Builder builder = new ViewDialog.Builder(this);
        // 设置标题
        final RegisterEditText editText = new RegisterEditText(this);
        // 限定发票抬头长度50
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
        if (viewId == R.id.editInvoice) {
            builder.setTitle(R.string.edit_noraml_invoice);
            editText.setText(userInvoices.getInvoiceHeader());
            editText.setSelection(editText.getText().length());
            builder.setContentView(editText);
        } else if (viewId == R.id.deleteInvoice) {
            builder.setTitle(R.string.noraml_invoice_dialog_del_msg);
        } else {
            builder.setTitle(R.string.add_noraml_invoice);
            editText.setHint(R.string.invoice_header_hint);
            builder.setContentView(editText);

        }
        // 设置Positive按钮点击监听
        builder.setPositiveButton(R.string.btn_confirm,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (viewId == R.id.editInvoice) {
                            // 隐藏软键盘
                            //                            CommonUtils.hideSoftInputFromWindow(getDelegate().getContext(), editText);
                            CommonUtils.hideSoftInputFromWindow(MyInvoiceActivity.this, editText);
                            if (!CommonUtils.isStringBlank(editText.getText().toString())) {
                                if (invoiceType == CommonConst.InvoiceConst.ID_NORMAL_INVOICE) {
                                    intentNoramalId = userInvoices.getInvoiceId();
                                }
                                ModifyInvoiceRequest modifyInvoiceRequest = new ModifyInvoiceRequest();
                                ModifyInvoiceModel modifyInvoiceModel = new ModifyInvoiceModel();
                                modifyInvoiceRequest.setToken(agent.getToken());
                                modifyInvoiceModel.setInvoiceHeader(editText.getText().toString());
                                modifyInvoiceModel.setInvoiceId(userInvoices.getInvoiceId());
                                modifyInvoiceModel.setInvoiceType(userInvoices.getInvoiceType());
                                modifyInvoiceRequest.setInvoice(modifyInvoiceModel);
                                modifyInvoice(modifyInvoiceRequest);
                                saveNoramlFlag = true;
                            } else {
                                ToastUtil.getInstance().show(R.string.invoice_header_not_null);
                            }
                        } else if (viewId == R.id.deleteInvoice) {
                            if (userInvoices.getInvoiceId() != null) {
                                DelInvoiceRequest delInvoiceRequest = new DelInvoiceRequest();
                                delInvoiceRequest.setToken(agent.getToken());
                                delInvoiceRequest.setInvoiceId(userInvoices.getInvoiceId());
                                delInvoice(delInvoiceRequest);
                            }

                        } else {
                            // 隐藏软键盘
                            //                            CommonUtils.hideSoftInputFromWindow(getDelegate().getContext(), editText);
                            CommonUtils.hideSoftInputFromWindow(MyInvoiceActivity.this, editText);
                            if (CommonUtils.isStringBlank(editText.getText().toString())) {
                                ToastUtil.getInstance().show(R.string.invoice_header_not_null);
                            } else {
                                if (editText.getText().toString().length() <= 50) {
                                    AddInvoiceRequest request = new AddInvoiceRequest();
                                    AddInvoiceModel addInvoiceModel = new AddInvoiceModel();
                                    request.setToken(agent.getToken());
                                    // 设置发票类型
                                    addInvoiceModel.setInvoiceType(NORMAL_INVOICE_TYPE);
                                    // 添加发票头
                                    addInvoiceModel.setInvoiceHeader(editText.getText().toString());

                                    request.setInvoice(addInvoiceModel);
                                    addInvoice(request);
                                } else {
                                    ToastUtil.getInstance().show(R.string.invoice_header_not_long);
                                }
                            }
                        }
                        dialog.dismiss();
                    }
                });

        // 设置Negative按钮点击监听
        builder.setNegativeButton(R.string.btn_cancel,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (viewId != R.id.deleteInvoice) {
                            //                            CommonUtils.hideSoftInputFromWindow(getDelegate().getContext(), editText);
                            CommonUtils.hideSoftInputFromWindow(MyInvoiceActivity.this, editText);
                        }
                        // 对话框关闭
                        dialog.dismiss();
                    }
                });
        // 创建对话框并显示
        builder.create().show();

    }

    /**
     * 删除发票信息
     */
    private void delInvoice(DelInvoiceRequest delInvoiceRequest) {
        //        danluTaskProxy.delInvoice(delInvoiceRequest, onDelNoramlInvoicesListener);
        agent.getApi().delInvoice(delInvoiceRequest).compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>() {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        ToastUtil.getInstance().show(R.string.del_sucess);
                        getInvoiceList();
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        String dispayMsg = "";
                        if (code.equals("1")){
                            dispayMsg = DanluApplication.get().getString(R.string.add_shopping_cart_error_1);
                        } else if (code.equals("2")) {
                            dispayMsg = DanluApplication.get().getString(R.string.invoice_dell_fail);
                            getInvoiceList();
                        }
                        return dispayMsg;
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "删除失败！" : displayMessage);
                    }
                });
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(MyInvoiceActivity.this, InvoiceMainActivity.class);
        intent.putExtra(CommonConst.IntentKey.INVOICE_ID, intentInvoiceType);
        intent.putExtra("InvoiceId", intentNoramalId);

        setResult(RESULT_OK, intent);
        super.onBackPressed();
    }

    private void initView() {
        llytBack = (LinearLayout) findViewById(R.id.llytBack);
        ptrdd = (PtrClassicFrameLayout) findViewById(R.id.ptrdd);
        invoiceContainer = (LinearLayout) findViewById(R.id.invoiceContainer);
        llytNoData = (LinearLayout) findViewById(R.id.llytNoData);
        llytHasData = (LinearLayout) findViewById(R.id.llytHasData);
        tvNoDataTitle1 = (TextView) findViewById(R.id.tv_no_data_title1);
        tvNoDataTitle2 = (TextView) findViewById(R.id.tv_no_data_title2);
        llytNormalInvoice = (LinearLayout) findViewById(R.id.llytNormalInvoice);
        llytVatInvoice = (LinearLayout) findViewById(R.id.llytVatInvoice);
        saveVatInvoice = (Button) findViewById(R.id.saveVatInvoice);
        tvInvoiceAddtxt = (TextView) findViewById(InvoiceAddtxt);
    }
}